import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'

Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    meta: {
      keep: true
    }

  },
  {
    path: '/new',
    name: 'new',
    component: () => import('../views/NewView.vue'),
    scrollBehavior() {
      return {
        x: 0,
        y: 0
      }
    }

  },
  {
    path: '/top',
    name: 'top',
    component: () => import('../views/TopView.vue')
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('../views/SearchView.vue')
  },
  {
    path: '/more',
    name: 'more',
    component: () => import('../views/MoreView.vue')
  },
  {
    path: '/pre',
    name: 'pre',
    component: () => import('../views/PreView.vue'),
    meta: {
      keep: true
    }
  },
  {
    path: '/reading',
    name: 'reading',
    component: () => import('../views/ReaDing.vue')
  },
  {
    path: '/cata',
    name: 'cata',
    component: () => import('../views/CataLogue.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/my',
    name: 'my',
    component: () => import('../views/MyView.vue'),
    beforeEnter: (to, from, next) => {
      console.log(to);
      console.log(from);
      let token = window.localStorage.getItem('token')
      if (!token) {
        next('/login');
        return
      } else {
        next()
      }
    }
  },
  {
    path: '/book',
    name: 'book',
    component: () => import('../views/BookShelf.vue'),
    beforeEnter: (to, from, next) => {
      console.log(to);
      console.log(from);
      let token = window.localStorage.getItem('token')
      if (!token) {
        next('/login');
        return
      } else {
        next()
      }
    }
  },
]
// 注意:解决路由跳转问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router